//
//  TogetherBuyViewController.m
//  PlayBall
//
//  Created by Jdd‘s macbook on 13-9-24.
//
//

#import "JddTogetherBuyViewController.h"
#import "JddFollowNumber.h"
#import "JddViewControllerManager.h"
#import "MLTableAlert.h"
#import "FloatLayer.h"
@interface JddTogetherBuyViewController (){
    NSInteger _floatLayerIndex;
    FloatLayer *_layer;
}

@end

@implementation JddTogetherBuyViewController
SHARED_VIEW_CONTROLLER_IMPLEMENT(JddTogetherBuyViewController);

@synthesize BuyShare;
@synthesize Share;

- (void)listSelect
{
    NoticeViewController *noticeView = [[NoticeViewController alloc] init];
    noticeView.webInfoId = LOTTERY_TYPE_ID_HEMAI_HELP;
    [self.navigationController pushViewController:noticeView animated:YES];

}
- (void)loadNavBar
{
    UIButton *right = [UIButton buttonWithType:UIButtonTypeCustom];
    right.frame = CGRectMake(0, 0, 40, 30);
    [right setTitle:@"帮助" forState:UIControlStateNormal];
    right.titleLabel.font = [UIFont systemFontOfSize:15];
    [right setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [right addTarget:self action:@selector(listSelect) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:right];

}
- (void)viewDidLoad
{
    [super viewDidLoad];
    _floatLayerIndex = 0;
//    [self.navigationItem setHidesBackButton:YES];
    [self loadNavBar];
   //self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;

    [self.tableView setSeparatorColor:SeparatorLineColor];
    if (IOS7) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    groupArray = [NSMutableArray arrayWithCapacity:0];
    resultArray = [NSMutableArray arrayWithCapacity:0];
    selectLotteryList = [[NSMutableArray alloc] initWithObjects:@"全部",@"竞彩足球",@"竞彩篮球",@"北单",@"胜负彩",@"任选九",@"双色球",@"超级大乐透",@"其它数字彩",nil];

    //初始化参数
    orderField = self.btn1.tag;
    orderType = 1;
    lottId = 0;
    lastButton = (UIButton *)[self.view viewWithTag:10];
    self.btn1.selected = YES;
    self.btn4.selected = YES;
    [self.view bringSubviewToFront:self.btn1];
    [self.view bringSubviewToFront:self.btn2];
    [self.view bringSubviewToFront:self.btn3];
    
    self.footButton.hidden = YES;

    lastButton = self.btn1;
    paixuImg_Down = [UIImage imageNamed:@"hemai_hall_jianTou_down_press.png"];
    paixuImg_Up = [UIImage imageNamed:@"hemai_hall_jianTou_up_press.png"];

//    //手势隐藏键盘
//    [self setOneTap];
//    //不遮挡键盘
//    [self setScroll];
    //初始化分页
    [self initPages];
    //获取彩种
    [self getLottery];
    
    //添加选择合买彩种按钮
    [self addRightBtn];
//    self.navigationItem.leftBarButtonItem = nil;
    //self.navigationItem.hidesBackButton = YES;
}

-(void)initSelectFirstTitle
{
    NSString *rBtnTitle = [rBtn titleForState:UIControlStateNormal];
    if ([rBtnTitle isEqualToString:@"合买大厅"]) {
        rBtnTitle = @"全部";
    }
    NSInteger selectRow = [selectLotteryList indexOfObject:rBtnTitle];
   
    self.lastIndexPath = [NSIndexPath indexPathForRow:selectRow inSection:0];
}

-(void)viewWillAppear:(BOOL)animated
{
//    [self.navigationItem setTitle:PAGE_TOGETHER_BUY];
    [super viewWillAppear:YES];
    [MobClick beginLogPageView:@"TogetherBuy"];
    [MobClick event:@"TAB-TogetherBuy"];

    [self.view setUserInteractionEnabled:YES];
    
    //显示tabbar
    [self setJddTabBarHidden:NO];
    [self setTabBarItemSelect:2];
    //初始化选择全部
    [self initSelectFirstTitle];
    
    //获取数据
    [self refresh2];

}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"TogetherBuy"];
    [self setJddTabBarHidden:YES];
}
- (IBAction)titleAction:(id)sender {
    UIButton *button = (UIButton *)sender;
    if(!button)
    {
        [self initPages];
        [self refresh2];
        return;
    }
    paixuBtn = (UIButton *)[self.view viewWithTag:button.tag+1];
    [paixuBtn setBackgroundImage:paixuImg_Down forState:UIControlStateSelected];

//    OrderType==0倒序  OrderType=1正序
//    OrderField：用于排序的列名（1：方案金额；2：佣金比例；3：进度；4剩余金额）
    
    //如果Btn是在选中状态下被点击的
    if (button == lastButton && button.selected == YES) {
        lastButton = button;
        //改变红色箭头方向
        if (orderType == 1) {
            [paixuBtn setBackgroundImage:paixuImg_Up forState:UIControlStateSelected];
            orderType = 0;
    
        } else if (orderType == 0) {
            [paixuBtn setBackgroundImage:paixuImg_Down forState:UIControlStateSelected];
            orderType = 1;
        }
        [self initPages];
        [self refresh2];
        
        return;
//        本次点击与上次点击不是同一个按钮
    } else {
        lastButton.selected = NO;
        lastButton = button;
        lastButton.selected = YES;
        orderType = 1;
        switch (button.tag) {
            case 10:
                orderField = 3;
                break;
            case 20:
                orderField = 2;
                break;
            case 30:
                orderField = 1;
                break;
            default:
                break;
        }
        [self initPages];
        [self refresh2];
    }
    self.btn4.selected = self.btn1.selected;
    self.btn5.selected = self.btn2.selected;
    self.btn6.selected = self.btn3.selected;
    
}

-(void)addRightBtn
{
    
    rv = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-140, 30)];
    
    rBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rBtn addTarget:self action:@selector(selectLottery) forControlEvents:UIControlEventTouchUpInside];
    [rBtn setTitle:@"合买大厅" forState:UIControlStateNormal];
    rBtn.titleLabel.font = [UIFont systemFontOfSize: 19.0];
    [rBtn setFrame:CGRectMake(0, 2, 180, 19)];
    rBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    UIImage *rBtnImg = LOADIMAGE(@"navBar_down");
    rImv = [[UIImageView alloc] initWithImage:rBtnImg];
    [self setRightBtnImage:@"合买大厅"];
    
    //创建的一个view，加入btn和图片
    [rv addSubview: rBtn];
    [rv addSubview:rImv];
    self.navigationItem.titleView = rv;
    
    //加入手势
    rImv.userInteractionEnabled = YES;
    UITapGestureRecognizer *recognizer=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectLottery)];
    [rImv addGestureRecognizer:recognizer];
}

-(void)setRightBtnImage:(NSString *)titleStr
{
    //    [rImv layoutToRightOf:rBtn AndSpace:0];
    
    JddSportNumber *btntitle = [[JddSportNumber alloc] init];
    btntitle.titleStr = titleStr;
    CGFloat width = [btntitle customWidth:19 font:19];
    rBtn.center = CGPointMake(90, 15);
    CGRect frame = rBtn.frame;
    frame.origin.x = (rv.width - width - 17) / 2;
    frame.size.width = width;
    rBtn.frame = frame;
    [rImv setFrame:CGRectMake(rBtn.frame.origin.x + width + 3, 10, 14, 10)];
}

//设置lottId
-(void)setRbtnTitle:(NSString *)title
{
    
    [rBtn setTitle:title forState:UIControlStateNormal];
    if ([title isEqualToString:@"合买大厅"]) {
        title = @"全部";
    }
    NSInteger row =  [selectLotteryList indexOfObject:title];
   lottId = [JddCommonFunction getTotetherBuyLottIdWithLotteryNameIndex:row];
   [self initPages];
    
   [self refresh2];
}


//设置彩种，后进行刷新数据
- (void)setLotteryContent:(NSInteger)tag{
    
    
    _floatLayerIndex = tag;
    [_layer loadFloatLayer:selectLotteryList withIndex:_floatLayerIndex];
    NSString *title = [selectLotteryList objectAtIndex:_floatLayerIndex];
    [self setRbtnTitle:title];
    //下拉箭头跟在彩种的后面
    [self setRightBtnImage:title];
    
}

-(void)selectLottery
{
    
    if (!_layer) {
        _layer = [[FloatLayer alloc] initWithFloatLayer:FloatLayerTogetherBuy withLayerCallBack:^(NSInteger index) {
            [self setLotteryContent:index];
        }];
    }
    
    [_layer loadFloatLayer:selectLotteryList withIndex:_floatLayerIndex];
    // create the alert
    /*
	self.alert = [MLTableAlert tableAlertWithTitle:@"请选择" cancelButtonTitle:@"取消" numberOfRows:^NSInteger (NSInteger section)
                  {
                  return selectLotteryList.count;
                  }
                andCells:^UITableViewCell* (MLTableAlert *anAlert, NSIndexPath *indexPath)
                  {
                  NSInteger row = indexPath.row;
                  static NSString *CellIdentifier = @"CellIdentifier";
                  UITableViewCell *cell = [anAlert.table dequeueReusableCellWithIdentifier:CellIdentifier];
                  if (cell == nil)
                      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                    cell.textLabel.text = [selectLotteryList objectAtIndex:row];
                    cell.textLabel.font = [UIFont systemFontOfSize:16];
                  NSUInteger oldRow = [self.lastIndexPath row];
                  cell.accessoryType = (row == oldRow && self.lastIndexPath != nil) ?
                  UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;
                  return cell;
                  }];
	
	// Setting custom alert height
	self.alert.height = 350;
    self.alert.lastIndexPath = self.lastIndexPath;
    // configure actions to perform
	[self.alert configureSelectionBlock:^(NSIndexPath *selectedIndex){
        self.lastIndexPath = self.alert.lastIndexPath;
        //得到alert的tableVew的显示位置
        self.alertTableViewContentOffset = self.alert.table.contentOffset;
        NSString *title = [selectLotteryList objectAtIndex:selectedIndex.row];
        [self setRbtnTitle:title];
        //下拉箭头跟在彩种的后面
        [self setRightBtnImage:title];
	} andCompletionBlock:^{
		
	}];
	
	// show the alert
	[self.alert show];
    //设置alert的tableVew的显示位置
    [self.alert.table setContentOffset:self.alertTableViewContentOffset animated:NO];
    */
}

-(void)getLottery
{
    JddQueryLotteryHallOperation *operation = [[JddQueryLotteryHallOperation alloc] init];
    operation.delegate= self;
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation ];
}
//合买选择 全部 的回调方法
-(void)QueryLotteryHallOperationResult:(NSData *)result
{
    if (result) {
        
    }
    //else {
//        [JddCommonFunction messageBoxWithMessage:[JddError sharedInstance].message];
//    }
    [JddCommonFunction setWaitingViewHidden:YES fromController:self];
}


- (void)setFooterView {
    CGFloat height = MAX(self.tableView.contentSize.height, self.tableView.frame.size.height);
    if (_refreshFooterView && [_refreshFooterView superview]) {
        
        _refreshFooterView.frame = CGRectMake(0.0f,
                                              height,
                                              self.tableView.frame.size.width,
                                              self.view.bounds.size.height);
        _refreshFooterView.delegate = self;
        [self.tableView addSubview:_refreshFooterView];
    } else {
        _refreshFooterView = [[EGORefreshTableFooterView alloc] initWithFrame:
                              CGRectMake(0.0f, height,
                                         self.tableView.frame.size.width, self.view.bounds.size.height)];
        _refreshFooterView.delegate = self;
        _refreshFooterView.mainTableHeight = self.tableView.frame.size.height;
        [self.tableView addSubview:_refreshFooterView];
    }
    
    if (_refreshFooterView) {
        [_refreshFooterView refreshLastUpdatedDate];
    }
}

- (void)removeFooterView {
    if (_refreshFooterView && [_refreshFooterView superview]) {
        [_refreshFooterView removeFromSuperview];
    }
    _refreshFooterView = nil;
}

#pragma mark -
#pragma mark method that should be called when the refreshing is finished

- (void)finishReloadingData {
	_reloading = NO;
    [_refreshFooterView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
    [self setFooterView];
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [_refreshFooterView egoRefreshScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [_refreshFooterView egoRefreshScrollViewDidEndDragging:scrollView];
}

#pragma mark -
#pragma mark EGORefreshTableDelegate Methods

- (void)egoRefreshTableDidTriggerRefresh:(EGORefreshPos)aRefreshPos {
    _reloading = YES;
    [self performSelector:@selector(refresh2) withObject:nil afterDelay:1];
}

- (BOOL)egoRefreshTableDataSourceIsLoading:(UIView*)view {
	return _reloading;
}

- (NSDate *)egoRefreshTableDataSourceLastUpdated:(UIView*)view {
	return [NSDate date];
}

-(void)initPages
{
    pageNo = 1;
    pageSize = 10;
    [resultArray removeAllObjects];
    [groupArray removeAllObjects];
}

//-(void)setOneTap{
//    UITapGestureRecognizer *oneTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoard)];
//    oneTap.delegate = self;
//    oneTap.numberOfTouchesRequired = 1;
//    [self.view addGestureRecognizer:oneTap];
//}
//
//-(void)hideKeyBoard
//{
//    [self.view endEditing:NO];
//}

//-(void)setScroll{
//    CGRect contentRect = CGRectZero;
//    for ( UIView *subview in self.scrollView.subviews ) {
//        contentRect = CGRectUnion(contentRect, subview.frame);
//    }
//    self.scrollView.contentSize = CGSizeMake(self.scrollView.bounds.size.width, CGRectGetMaxY(contentRect));
//}

-(IBAction)refresh2
{
    if ([resultArray count] < 10) {
        pageNo = 0;
    }
    pageNo ++;
    
    [JddCommonFunction setWaitingViewHidden:NO fromController:self];
    JddTogetherBuyOperation *operation = [[JddTogetherBuyOperation alloc] init];
    operation.delegate = self;
    operation.pageSize = pageSize;
    operation.PageNo = pageNo;
    operation.OrderField = orderField;
    operation.OrderType = orderType;
    operation.lottId = lottId;
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
}
#pragma mark 合买大厅数据请求结果
-(void)TogetherBuyOperationResult:(NSData *)result{
    int resultCount = 0;
    if ([JddDataParser parseTogetherBuyResult:result]) {
        //主要用于判断是否还有新数据加载
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingMutableContainers error:nil];
        NSString *dictStr = [dict objectForKey:@"Data"];
        NSDictionary *subDict = [NSJSONSerialization JSONObjectWithData: [dictStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
        resultCount = [[subDict objectForKey:@"Count"]intValue];

        //解析并存入数据
        [resultArray removeAllObjects];
        [JddDataParser parseSportResult:result bankArray:resultArray];
        for (int i=0; i< resultArray.count; ++i) {
            JddFollowNumber *follownum = [[JddFollowNumber alloc]init];
            follownum.open = 0;
            [groupArray addObject:follownum];
        }
        [self.tableView reloadData];
    } else {
        [JddCommonFunction messageBoxWithMessage:[JddError sharedInstance].message];
    }
   
    //数据低于10条或没有新数据时隐藏“查看更多”
    if ([resultArray count] < 10 || resultCount == 0) {
        _refreshFooterView.hidden = YES;
        self.footButton.hidden = YES;
    } else {
        _refreshFooterView.hidden = NO;
        self.footButton.hidden = NO;
    }
    [JddCommonFunction setWaitingViewHidden:YES fromController:self];
    //下拉刷新
//    [self finishReloadingData];
}
#pragma mark 合买详情数据请求结果
-(void)QueryBuyHistoryDetailOperationResult:(NSData *)result{
    [JddCommonFunction setWaitingViewHidden:YES fromController:self];
    if (result) {
        NSString *resultString = [JddDataParser parseBuyHistoryDetailResult:result];
        if (resultString == nil) {
            [JddCommonFunction messageBoxWithMessage:[JddError sharedInstance].message];
        }else {
            if (isBuy) {
                isBuy = NO;
                NSDictionary *buydetail = [resultString objectFromJSONString];
                lssueString = [buydetail objectForKey:@"Issue"];
                //参于合买
                [self joinToghterBuyAction];
            }else{
                [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_TOGETHER_BUY_DETAIL
                                                                        fromController:self
                                                                            withObject:resultString
                                                                           withObject2:detailData];
                
            }
        }
        
    }
}

#pragma mark tableView 的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([groupArray count]>0) {
        JddFollowNumber *groupDic = [groupArray objectAtIndex:section];
        if (groupDic.open==0) {
            return 0;
        }else {
            return 1;
        }
    }else {
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 85.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 55.0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView endEditing:YES];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [resultArray count];
}

-(void)sportTeamButtonHeadClicked:(NSNumber*)position
{
//    [self hideKeyBoard];
    
    JddFollowNumber *groupDic = [groupArray objectAtIndex:[position intValue]];
    //设置groupDic中的展开状态
    if(groupDic.open == 0){
        groupDic.open = 1;
    }else {
        groupDic.open = 0;

    }
    
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:[position intValue]]
                  withRowAnimation:UITableViewRowAnimationFade];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString *CellIdentifier = @"TogetherBuyItemCellHeaderIdentifier";
    JddTogetherBuyItemCellHeader *cell = (JddTogetherBuyItemCellHeader *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(nil == cell) {
        cell = [JddTogetherBuyItemCellHeader getInstanceView];
    }
    NSDictionary *d = [resultArray objectAtIndex:section];
    cell.statePosition = [NSNumber numberWithInt:section];
    
    if ([groupArray count] > 0) {
		JddFollowNumber *groupDic = [groupArray objectAtIndex:section];
		if (groupDic.open == 0) {
			cell.jianTou.image = [UIImage imageNamed:@"hemai_hall_down.png"];
		}
		else {
			cell.jianTou.image = [UIImage imageNamed:@"hemai_up.png"];
		}
	}
    //百分比1
    NSInteger schedule = [[d objectForKey:@"Schedule"] integerValue];
    CGRect frame = cell.baiFenHao.frame;
    if (schedule > 99 ) {
        frame.origin.x = 79;
    }
    cell.baiFenHao.frame = frame;
    
    //跟单人数
    NSString *merchandiserCount = [NSString stringWithFormat:@"%@人",[[d objectForKey:@"MerchandiserCount"] stringValue]];
    
    //用户名
    NSString *uName = [d objectForKey:@"UName"];
    //彩种名
    NSString *lottName = [d objectForKey:@"LottName"];
    if ([lottName isEqualToString:@"超级大乐透"]) {
        lottName = @"大乐透";
    }else{
        lottName = [d objectForKey:@"LottName"];
    }
//    NSString *bScale = [[d objectForKey:@"BScale"]stringValue];
    NSString *share = [NSString stringWithFormat:@"￥%@", [[d objectForKey:@"Share"] stringValue]];
    NSString *rShare = [NSString stringWithFormat:@"￥%@", [[d objectForKey:@"RShare"] stringValue]];
    //百分比2
    NSString *assure = [[d objectForKey:@"Assure"] stringValue];
    if ([assure isEqualToString:@"0"]) {
        assure = @"";
        cell.baoLabel.hidden = YES;
    }
    if (schedule < 100) {
        cell.scheduleLbl.text = [NSString stringWithFormat:@"%02d",schedule];
    } else {
        cell.scheduleLbl.text = [NSString stringWithFormat:@"%d",schedule];
    }
    cell.scheduleLbl.textAlignment = NSTextAlignmentCenter;
    cell.uNameLbl.text = uName;
    
    //图片等级
    NSString *level = [[d objectForKey:@"Level"] stringValue];
    UIImage *levelImg = [JddCommonFunction getImgByLevel:level];
    //计算等级图标的宽
    CGFloat wid; //= [level integerValue]%5*15;
    if ([level integerValue]%5 == 0) {
        wid = 5*14;
    } else {
        wid = [level integerValue]%5*14;
    }
    [cell.levelIV layoutToRightOf:cell.uNameLbl AndSpace:3];
    //获取等级图片
    cell.levelIV.frame = CGRectMake(cell.levelIV.frame.origin.x, 12, wid, 15);
    cell.levelIV.Image = levelImg;
    //    cell.levelIV.contentMode = UIViewContentModeScaleToFill;

    
    cell.lottNameLbl.text = lottName;
    cell.shareLbl.text = share;
    cell.rShareLbl.text = rShare;
    cell.merchandiserCount.text = merchandiserCount;
    cell.delegate = self;
    return cell;
}

#pragma mark  合买详情operation
-(void)detailAction:(NSNumber *)section
{
    detailData = [[NSDictionary alloc] init];
    detailData = [resultArray objectAtIndex:[section integerValue]];
    self.SchemeID = [detailData objectForKey:@"SchemeID"];
    self.uName = [detailData objectForKey:@"UName"];
    self.isYsq = [[detailData objectForKey:@"IsYsq"] boolValue];
    self.level = [[detailData objectForKey:@"Level"] stringValue];
    self.EndTime = [detailData objectForKey:@"EndTime"];
    self.Share = [[detailData objectForKey:@"Share"] intValue];
    
    JddQueryBuyHistoryDetailOperation *operation = [[JddQueryBuyHistoryDetailOperation alloc] init];
    //百分比1
    NSString *schedule = [[[detailData objectForKey:@"Schedule"] stringValue] stringByAppendingString:@"%"];
    //百分比2
    NSString *assure = [[detailData objectForKey:@"Assure"] stringValue];
    if ([assure isEqualToString:@"0"]) {
        assure = @"";
    }else{
        assure = [[NSString stringWithFormat:@"+%@", assure] stringByAppendingString:@"%"];
    }
    self.jd = [schedule stringByAppendingString:assure];
    operation.SchemeId = self.SchemeID;
    operation.DataSource = @"1";
    operation.delegate = self;
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
    [JddCommonFunction setWaitingViewHidden:NO fromController:self];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger section = indexPath.section;
    static NSString *CellIdentifier = @"TogetherBuyItemCellIdentifier";
    JddTogetherBuyItemCell *cell = (JddTogetherBuyItemCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(nil == cell) {
        cell = [JddTogetherBuyItemCell getInstanceView];
    }
    NSDictionary *result = [resultArray objectAtIndex:indexPath.section];
    float jinDu = [[result objectForKey:@"Schedule"] floatValue];
    if (jinDu >= 100.0f) {
        cell.liGiBuy.enabled = NO;
    }
    cell.section = [NSNumber numberWithInteger:section];
    cell.delegate = self;
    cell.moneyText.delegate = self;
    return cell;
}

//全包
-(void)qbAction:(NSNumber *)section
{
//    [self hideKeyBoard];
    NSDictionary *result = [resultArray objectAtIndex:[section integerValue]];
    NSString *rShare = [[result objectForKey:@"RShare"] stringValue];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:[section integerValue]];
   JddTogetherBuyItemCell *cell = (JddTogetherBuyItemCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    cell.moneyText.text = rShare;
}

//购买
-(void)buyAction:(NSNumber *)section
{
//    [self hideKeyBoard];
    
    if ([JddCommonFunction isLogin]) {
        NSDictionary *result = [resultArray objectAtIndex:[section integerValue]];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:[section integerValue]];
        JddTogetherBuyItemCell *cell = (JddTogetherBuyItemCell *)[self.tableView cellForRowAtIndexPath:indexPath];
        int money = [cell.moneyText.text intValue];
        int rShare = [[result objectForKey:@"RShare"] intValue];
        self.BuyShare = money;
        self.SchemeID = [result objectForKey:@"SchemeID"];
        self.EndTime = [result objectForKey:@"EndTime"];
        self.Share = [[result objectForKey:@"Share"] intValue];
        self.LottName = [result objectForKey:@"LottName"];
        if ([self.LottName isEqualToString:@"超级大乐透"]) {
            self.LottName = @"大乐透";
        }
        if (money == 0) {
            //金额不能为空
            [JddCommonFunction messageBoxWithMessage:TOGETHER_BUY_NOT_EMPTY];
        }else if(money > rShare){
            //不能超出认购金额
            [JddCommonFunction messageBoxWithMessage:TOGETHER_BUY_NOT_RSHARE];
        }else{
//            [self hideKeyBoard];
            //确认购买 先去获取详细信息
            [self getLssueString];
            /*
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"玩球球"                                                            message:TOGETHER_BUY_SURE
                                                           delegate:self
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:@"取消",nil ];
            [alert show];
            */
        }
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"  message:LOGIN_SURE
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:@"取消",nil ];
        [alert show];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([[alertView message] isEqualToString:LOGIN_SURE]) {
        if (buttonIndex == 0) {
            [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_LOGIN
                                                                 fromController:self
                                                                     withObject:nil
                                                                    withObject2:nil];
        }
    }else if ([[alertView message] isEqualToString:TOGETHER_BUY_SURE]) {
        if (buttonIndex == 0) {
            //获取期次
            [self getLssueString];
        }
    }
}


-(void)getLssueString
{
    isBuy = YES;
    JddQueryBuyHistoryDetailOperation *operation = [[JddQueryBuyHistoryDetailOperation alloc] init];
    operation.SchemeId = self.SchemeID;
    operation.DataSource = @"1";
    operation.delegate = self;
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
    [JddCommonFunction setWaitingViewHidden:NO fromController:self];
}

-(void)joinToghterBuyAction
{
    [JddCommonFunction setWaitingViewHidden:NO fromController:self];
    JddJoinTogetherBuyOperation *operation = [[JddJoinTogetherBuyOperation alloc] init];
    operation.delegate= self;
    operation.SchemeID = self.SchemeID;
    operation.DataSource = 1;
    operation.BuyShare = self.BuyShare;
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
}

-(void)initAlert
{
    alert1 = [JddTGAlertView getInstanceView];
    alert1.moneylable = [NSString stringWithFormat:@"%d彩豆", self.BuyShare];
    alert1.typestring = @"合买";
    alert1.lssueString = lssueString;
    alert1.faMoney = [NSString stringWithFormat:@"%d彩豆", self.Share];
    alert1.fromview = self;
    alert1.delegate = self;
}

-(void)JoinTogetherBuyOperationResult:(NSData *)result{
    [JddCommonFunction setWaitingViewHidden:YES fromController:self];
//    if(result)
//    {
//        NSDictionary *ReDic = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingMutableContainers error:nil];
//        if([[ReDic objectForKey:@"Code"] intValue] == 0)
//        {
//            NSString*checkUrlString = [NSString stringWithFormat:@"%@?ck=%@",BASE_SERVER_IOS_BUY_LOTTERY_URL,[ReDic objectForKey:@"Data"]];
//            NSURL *checkUrl = [NSURL URLWithString:checkUrlString];
//            [[UIApplication sharedApplication] openURL:checkUrl];
//        }
//        else
//        {
//            [JddCommonFunction messageBoxWithMessage:[ReDic objectForKey:@"Data"]];
//        }
//    }
    [self initAlert];
    if (result) {
        if ([JddDataParser parseBuyResult:result]){
            //更新近期购买彩种
            [JddCommonFunction updateBuyLotteryListWithLotteryId:[JddCommonFunction getLotteryIdByName:self.LottName]];
            [alert1 alertMessage:@"认购成功"];
        }
        else {
            [alert1 alertMessage:[JddError sharedInstance].message];
        }
        [alert1 show];
    }
}
////放弃所有可能的第一响应 收键盘
//-(void)resignAllResponder:(UIView*)parentView
//{
//    for (UIView *view in parentView.subviews) {
//        if ([view isKindOfClass:[UITextField class]]) {
////            [self moveBack];
//            [view resignFirstResponder];
//        }
//        else {
//            
//            if ([view.subviews count] != 0) {
//                [self resignAllResponder:view];
//            }
//        }
//    }
//}

-(void)tbuy{
    [self refresh2];
}
@end
